package com.course.servlet;

import com.course.entity.Student;
import com.course.service.StudentService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    private final StudentService studentService;

    public RegisterServlet() {
        this.studentService = new StudentService();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 获取表单数据
        String studentNumber = request.getParameter("studentNumber");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String confirmPassword = request.getParameter("confirmPassword");
        String name = request.getParameter("name");
        String gender = request.getParameter("gender");
        String className = request.getParameter("className");
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");

        // 验证密码
        if (!password.equals(confirmPassword)) {
            request.setAttribute("error", "两次输入的密码不一致");
            request.getRequestDispatcher("register.jsp").forward(request, response);
            return;
        }

        // 创建学生对象
        Student student = new Student();
        student.setStudentId(studentNumber);
        student.setUsername(username);
        student.setPassword(password);
        student.setName(name);
        student.setGender(gender);
        student.setClassName(className);
        student.setEmail(email);
        student.setPhone(phone);

        // 注册学生
        boolean success = studentService.register(student);

        if (success) {
            // 注册成功，重定向到登录页面
            response.sendRedirect("login.jsp");
        } else {
            // 注册失败，返回错误信息
            request.setAttribute("error", "注册失败，用户名或学号可能已存在");
            request.getRequestDispatcher("register.jsp").forward(request, response);
        }
    }
} 